from rest_framework import serializers
from .models import User, Topic, Announcement
from django.conf import settings
import os

class UserSerializer(serializers.ModelSerializer):
    # avatar = serializers.SerializerMethodField()

    class Meta:
        model = User
        fields = ('id', 'username', 'password', 'nickname', 'email', 'gender', 'avatar', 'desc', 'isAdmin')
        extra_kwargs = {
            'password': {'write_only': True}
        }

    def update(self, instance, validated_data):
        for attr, value in validated_data.items():
            setattr(instance, attr, value)
        instance.save()
        return instance

    # 获取绝对路径
    def to_representation(self, instance):
        representation = super().to_representation(instance)
        if representation['avatar']:
            # 获取图片的相对路径
            photo_relative_path = representation['avatar']
            # 拼接基本 URL 和图片相对路径
            representation['avatar'] = settings.BASE_URL + photo_relative_path
        return representation

    def get_avatar(self, obj):
        if obj.avatar:
            return obj.avatar.url
        return None

class TopicSerializer(serializers.ModelSerializer):

    class Meta:
        model = Topic
        fields = ('id', 't_uid', 't_title', 't_content', 't_kind', 'create_time', 't_photo', 't_introduce', 'recommend')
        read_only_fields = ('create_time',)

    def create(self, validated_data):
        return Topic.objects.create(**validated_data)

    def update(self, instance, validated_data):
        for attr, value in validated_data.items():
            setattr(instance, attr, value)
        instance.save()
        return instance

    # 获取绝对路径
    def to_representation(self, instance):
        representation = super().to_representation(instance)
        if representation['t_photo']:
            # 获取图片的相对路径
            photo_relative_path = representation['t_photo']
            # 拼接基本 URL 和图片相对路径
            representation['t_photo'] = settings.BASE_URL + photo_relative_path
        return representation

class AnnouncementSerializer(serializers.ModelSerializer):
    a_username = serializers.CharField(source='a_uid.username', read_only=True)

    class Meta:
        model = Announcement
        fields = ['id', 'a_uid', 'a_username', 'a_content', 'a_create_time']
        read_only_fields = ['id', 'a_create_time']

    def create(self, validated_data):
        return Announcement.objects.create(**validated_data)